package com.coscon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coscon.mapper.SysConfigMapper;
import com.coscon.model.db.SysConfig;
import com.coscon.service.ConfigService;
import com.coscon.utils.DateUtils;
import com.coscon.utils.XSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ConfigServiceImpl implements ConfigService  {

    @Resource
    private SysConfigMapper sysConfigMapper;


    @Override
    @Transactional
    public boolean saveSecurityConfig(Map<String, String[]> requestP) {
        boolean f =false;
        if(requestP==null || requestP.isEmpty()){
            return f;
        }
        //处理request其他参数
        Map<String,String> map = new HashMap<>();
        Iterator<Map.Entry<String, String[]>> keyIter = requestP.entrySet().iterator();
        while(keyIter.hasNext()) {
            Map.Entry<String, String[]> entry = keyIter.next();
            String[] vals = entry.getValue();
            String val = null;
            if(vals!=null && ArrayUtils.isNotEmpty(vals)){
                val = vals[0];
            }
            map.put(entry.getKey(),val);
        }
        log.info(map.toString());
        //开始处理
        String securityIsUser = map.get("security_is_user")!=null?map.get("security_is_user").toString():"";
        String securityPasswordType = map.get("security_password_type")!=null?map.get("security_password_type").toString():"";
        String securityCustomPassword = map.get("security_custom_password")!=null?map.get("security_custom_password").toString():"";
        String securityIsFileDownload = map.get("security_is_file_download")!=null?map.get("security_is_file_download").toString():"";
        String securitySaveDownloadLog = map.get("security_save_download_log")!=null?map.get("security_save_download_log").toString():"";
        String securityIsScreenCapture = map.get("security_is_screen_capture")!=null?map.get("security_is_screen_capture").toString():"";
        String securityIsWakeLan = map.get("security_is_wake_lan")!=null?map.get("security_is_wake_lan").toString():"";
        String securityIsFtp = map.get("security_is_ftp")!=null?map.get("security_is_ftp").toString():"";
        String securityFtpUsername = map.get("security_ftp_username")!=null?map.get("security_ftp_username").toString():"";
        String securityFtpPassword = map.get("security_ftp_password")!=null?map.get("security_ftp_password").toString():"";
        String securityFtpRootDir = map.get("security_ftp_root_dir")!=null?map.get("security_ftp_root_dir").toString():"";
        String securityFtpPort = map.get("security_ftp_port")!=null?map.get("security_ftp_port").toString():"";
        String securitySystemUsername = map.get("security_system_username")!=null?map.get("security_system_username").toString():"";
        this.saveOrUpdateConfig("security_is_user",securityIsUser);
        this.saveOrUpdateConfig("security_password_type",securityPasswordType);
        this.saveOrUpdateConfig("security_custom_password",securityCustomPassword);
        this.saveOrUpdateConfig("security_is_file_download",securityIsFileDownload);
        this.saveOrUpdateConfig("security_save_download_log",securitySaveDownloadLog);
        this.saveOrUpdateConfig("security_is_screen_capture",securityIsScreenCapture);
        this.saveOrUpdateConfig("security_is_wake_lan",securityIsWakeLan);
        this.saveOrUpdateConfig("security_is_ftp",securityIsFtp);
        this.saveOrUpdateConfig("security_ftp_username",securityFtpUsername);
        this.saveOrUpdateConfig("security_ftp_password",securityFtpPassword);
        this.saveOrUpdateConfig("security_ftp_root_dir",securityFtpRootDir);
        this.saveOrUpdateConfig("security_ftp_port",securityFtpPort);
        this.saveOrUpdateConfig("security_system_username",securitySystemUsername);

        f = true;
        return f;
    }

    @Override
    @Transactional
    public boolean saveLogConfig(Map<String, String[]> formData) {
        boolean f =false;
        if(formData==null || formData.isEmpty()){
            return f;
        }
        //处理request其他参数
        Map<String,String> map = new HashMap<>();
        Iterator<Map.Entry<String, String[]>> keyIter = formData.entrySet().iterator();
        while(keyIter.hasNext()) {
            Map.Entry<String, String[]> entry = keyIter.next();
            String[] vals = entry.getValue();
            String val = null;
            if(vals!=null && ArrayUtils.isNotEmpty(vals)){
                val = vals[0];
            }
            map.put(entry.getKey(),val);
        }
        log.info(map.toString());
        //开始处理
        String syslogPlayFileLog = map.get("syslog_play_file_log")!=null?map.get("syslog_play_file_log").toString():"";
        String syslogDeleteFileLog = map.get("syslog_delete_file_log")!=null?map.get("syslog_delete_file_log").toString():"";
        String syslogCmdExecLog = map.get("syslog_cmd_exec_log")!=null?map.get("syslog_cmd_exec_log").toString():"";
        String syslogLoginLog = map.get("syslog_login_log")!=null?map.get("syslog_login_log").toString():"";
        this.saveOrUpdateConfig("syslog_play_file_log",syslogPlayFileLog);
        this.saveOrUpdateConfig("syslog_delete_file_log",syslogDeleteFileLog);
        this.saveOrUpdateConfig("syslog_cmd_exec_log",syslogCmdExecLog);
        this.saveOrUpdateConfig("syslog_login_log",syslogLoginLog);
        f = true;
        return f;
    }

    @Override
    @Transactional
    public boolean saveFileConfig(Map<String, String[]> formData) {
        boolean f =false;
        if(formData==null || formData.isEmpty()){
            return f;
        }
        //处理request其他参数
        Map<String,String> map = new HashMap<>();
        Iterator<Map.Entry<String, String[]>> keyIter = formData.entrySet().iterator();
        while(keyIter.hasNext()) {
            Map.Entry<String, String[]> entry = keyIter.next();
            String[] vals = entry.getValue();
            String val = null;
            if(vals!=null && ArrayUtils.isNotEmpty(vals)){
                val = vals[0];
            }
            map.put(entry.getKey(),val);
        }
        log.info(map.toString());
        //开始处理
        String fileDeleteAction = map.get("file_delete_action")!=null?map.get("file_delete_action").toString():"";
        String fileViewExtType = map.get("file_view_ext_type")!=null?map.get("file_view_ext_type").toString():"";
        String fileViewExtVideo = map.get("file_view_ext_video")!=null?map.get("file_view_ext_video").toString():"";
        String fileViewExtAudio = map.get("file_view_ext_audio")!=null?map.get("file_view_ext_audio").toString():"";
        String fileViewExtOffice = map.get("file_view_ext_office")!=null?map.get("file_view_ext_office").toString():"";
        String fileViewDefaultRootDir = map.get("file_view_default_root_dir")!=null?map.get("file_view_default_root_dir").toString():"";
        String fileViewSaveLastDir = map.get("file_view_save_last_dir")!=null?map.get("file_view_save_last_dir").toString():"";
        String fileViewSaveDirLog = map.get("file_view_save_dir_log")!=null?map.get("file_view_save_dir_log").toString():"";
        String fileViewAnalysisAction = map.get("file_view_analysis_action")!=null?map.get("file_view_analysis_action").toString():"";
        String fileViewHiddenFile = map.get("file_view_hidden_file")!=null?map.get("file_view_hidden_file").toString():"";
        String fileViewHiddenFolder = map.get("file_view_hidden_folder")!=null?map.get("file_view_hidden_folder").toString():"";
        String fileViewFileSort = map.get("file_view_file_sort")!=null?map.get("file_view_file_sort").toString():"";
        String fileIsDeleteFile = map.get("file_is_delete_file")!=null?map.get("file_is_delete_file").toString():"";
        String fileViewListMinMb = map.get("file_view_list_min_mb")!=null?map.get("file_view_list_min_mb").toString():"";

        this.saveOrUpdateConfig("file_delete_action",fileDeleteAction);
        this.saveOrUpdateConfig("file_view_ext_type",fileViewExtType);
        this.saveOrUpdateConfig("file_view_ext_video",fileViewExtVideo);
        this.saveOrUpdateConfig("file_view_ext_audio",fileViewExtAudio);
        this.saveOrUpdateConfig("file_view_ext_office",fileViewExtOffice);
        this.saveOrUpdateConfig("file_view_default_root_dir",fileViewDefaultRootDir);
        this.saveOrUpdateConfig("file_view_save_last_dir",fileViewSaveLastDir);
        this.saveOrUpdateConfig("file_view_save_dir_log",fileViewSaveDirLog);
        this.saveOrUpdateConfig("file_view_analysis_action",fileViewAnalysisAction);
        this.saveOrUpdateConfig("file_view_hidden_file",fileViewHiddenFile);
        this.saveOrUpdateConfig("file_view_hidden_folder",fileViewHiddenFolder);
        this.saveOrUpdateConfig("file_view_file_sort",fileViewFileSort);
        this.saveOrUpdateConfig("file_is_delete_file",fileIsDeleteFile);
        this.saveOrUpdateConfig("file_view_list_min_mb",fileViewListMinMb);
        f = true;
        return f;
    }

    @Override
    public Map<String, String> getSysconfigValByKeys(String... keys) {
        Map<String, String> map = new HashMap<>(16);
        if (ArrayUtils.isEmpty(keys)) {
            return map;
        }
        List<SysConfig> list = this.sysConfigMapper.getSysconfigValByKeys(keys);
        if (list != null && !list.isEmpty()) {
            for (SysConfig c : list) {
                String key = c.getConfigKey();
                if (!map.containsKey(key)) {
                    map.put(key, c.getConfigVal());
                }
            }
        }
        return map;
    }

    @Override
    public Map<String, String> getSysconfigValRightLikeByKey(String keyRightMatching) {
        Map<String, String> map = new HashMap<>(16);
        if (StringUtils.isBlank(keyRightMatching)) {
            return map;
        }
        List<SysConfig> list = this.sysConfigMapper.getSysconfigValRightLikeByKey(keyRightMatching);
        if (list != null && !list.isEmpty()) {
            for (SysConfig c : list) {
                String key = c.getConfigKey();
                if (!map.containsKey(key)) {
                    map.put(key, c.getConfigVal());
                }
            }
        }
        return map;
    }


    @Override
    public String getSysconfigValByKey(String key) {
        String val = null;
        if (StringUtils.isEmpty(key)) {
            return val;
        }
        QueryWrapper<SysConfig> qw = new QueryWrapper<>();
        qw.eq("CONFIG_KEY", key);
        IPage<SysConfig> pageObj = new Page<>(1, 1);
        //执行查询
        pageObj = this.sysConfigMapper.selectPage(pageObj, qw);
        if (pageObj.getRecords() != null && !pageObj.getRecords().isEmpty()) {
            val = pageObj.getRecords().get(0).getConfigVal();
            if(StringUtils.isNotBlank(val)){
                val = XSSUtils.xssDecodeParameter(val);
            }
        }
        return val;
    }

    @Override
    @Transactional
    public String saveOrUpdateConfig(String key, String val) {
        String id = null;
        if(StringUtils.isBlank(key)){
            return id;
        }
        SysConfig config = this.sysConfigMapper.getConfigByKey(key);
        if(config==null){//新增
            config = new SysConfig();
            config.setConfigKey(key);
            config.setConfigVal(val);
            config.setUpDateTime(DateUtils.nowStr());
            if(this.sysConfigMapper.insert(config)>0){
                id = config.getConfigId();
            }
        }else{//更新
            config.setConfigVal(val);
            config.setUpDateTime(DateUtils.nowStr());
            if(this.sysConfigMapper.updateById(config)>0){
                id = config.getConfigId();
            }
        }
        return id;
    }


}
